package com.obsidian.free.slideshow;

import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Contacts;
import android.widget.RemoteViews;

public class SlideshowUpdateService extends Service {
   final static public int SIZE_SMALL = 0;
   final static public int SIZE_MEDIUM = 1;
   final static public int SIZE_LARGE = 2;
   
   private static int size; 

   @Override
   public void onStart(Intent intent, int startId) {
      super.onStart(intent, startId);
      
      int appWidgetId = intent.getIntExtra("appWidgetId", AppWidgetManager.INVALID_APPWIDGET_ID);
      size = intent.getIntExtra("size", SIZE_SMALL);
      RemoteViews update = null;
      update = buildUpdate(this, appWidgetId);
      
      AppWidgetManager manager = AppWidgetManager.getInstance(this);
      manager.updateAppWidget(appWidgetId, update);
   }
   
   public static RemoteViews buildUpdate(Context context, int appWidgetId) {
      RemoteViews view = new RemoteViews(context.getPackageName(), R.layout.widget_frame);
      
      ImageDatabase db = new ImageDatabase(context);
      if(db.needsUpdate(appWidgetId)) {
         Bundle widget = db.getWidget(appWidgetId);
         int current = widget.getInt(ImageDatabase.WIDGETS_CURRENT);
         Bitmap dbbm = db.getImage(appWidgetId, current);
         Bitmap bm = Bitmap.createBitmap(dbbm);
         view.setImageViewBitmap(R.id.Image, bm);
         
         Intent configIntent = new Intent(context, SlideshowClickOptions.class);
         Uri data = ContentUris.withAppendedId(Contacts.People.CONTENT_URI, (int)appWidgetId);
         configIntent.setData(data);
         configIntent.putExtra("wid", appWidgetId);
         configIntent.putExtra("size", size);
         PendingIntent pending = PendingIntent.getActivity(context, 0, configIntent, PendingIntent.FLAG_UPDATE_CURRENT);
         view.setOnClickPendingIntent(R.id.Frame, pending);
      }
      db.close();
      
      return view;
   }
   
   @Override
   public IBinder onBind(Intent intent) {
      return null;
   }

}
